#!groovy

@Library('jenkinslib@master') _

def tools = new org.devops.tools()
def model = new org.devops.modules()
def dingmes = new org.devops.ding()
String srcUrl = ""
String branchName = ""
String proName = ""
try{
    srcUrl = srcUrl_auto
    //仓库分支(只处理dev)
    branchName = "dev"
    //微服务名称
    //String proName = proName_auto.split('/')[0]
    proName = "./"
    //环境
    instructions = "<font color=#FF0000>开发(全自动)</font>"
    //只处理dev
    if(ref.split('/')[-1] != "dev"){
        tools.PrintMes("只处理dev",'red')
        exit()
    }
} catch (Exception e){
    tools.PrintMes("非自动化","blue")
    //gitlab仓库地址
    srcUrl = "${env.srcUrl}"
    srcUrl = srcUrl.split("\\(")[0].trim()
    //仓库分支
    branchName = "${env.branchName}"
    //微服务名称
    proName = "${env.proName}"
    proName = proName.split("\\(")[0].trim()
    //环境
    instructions = "开发(手动)"
}
println srcUrl
def workdir = ''
def pronames = ''
//代码作者
def Author = ''
//更新记录(3条)
def ChangeLog = ''

//pipeline
pipeline{
    agent any    
    stages{

       stage("GetCode"){
            steps{
                script{
                    workdir = srcUrl.split('/')[-1].split('.git')[0]
                    if(!workdir) {
                        println "获取工作目录失败"
                        exit()
                    }
                     tools.PrintMes("获取代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: '87886427-ebc2-4f45-8921-dcf38f80867e', url: "${srcUrl}"]]])
                        //代码作者
                        res = sh returnStdout: true ,script: "cd ${workdir}/${proName} && git log -1|grep Author |awk '{print \$2}'"
                        Author = res.trim()
                        //更新记录(5条)
                        tmp_shell="""
                            cd ${workdir}/${proName}
                            git log -3 |awk '!/^\$/' |awk '/^Author|^commit/ {next}{printf "%s\\n",\$0}'
                        """
                        res = sh returnStdout: true ,script: "${tmp_shell}"
                        ChangeLog = res.trim()
                        pronames = model.pronames(proName,workdir)
                        //创建jenkins临时目录
                        sh "mkdir -p ${workdir}/${proName}/jenkins_tmp"
                }
            }
       }
       stage("Build"){
            steps{
                script{
                    tools.PrintMes("执行npm编译","green")
                    //清除已有dist文件
                    sh "cd ${workdir} && cd ${proName} && cd jenkins_tmp && rm -rf dist"
                    if (workdir=="esignservice-app"){
                        sh "cd ${workdir} && cd ${proName} && npm install"
                        sh "cd ${workdir} && cd ${proName} && npm run build:h5"
                    }else{
                        sh "cd ${workdir} && cd ${proName} && cnpm install"
                        sh "cd ${workdir} && cd ${proName} && npm run build:prod"
                    }
                    //将dist文件放入临时目录
                    sh """
                        mv -f ${workdir}/${proName}/dist ${workdir}/${proName}/jenkins_tmp/
                        cd ${workdir}/${proName}/jenkins_tmp/dist
                        tar zcf dist.tar.gz *
                        """
                }
            }
        }
        stage("Deploy"){
            steps{
                script{
                    tools.PrintMes("部署","green")                
                        if (workdir=="esignservice-app"){
                            sh "ssh root@172.16.1.126 \"rm -rf /usr/local/nginx/app/*\""
                            sh "scp ${workdir}/${proName}/jenkins_tmp/dist/dist.tar.gz root@172.16.1.126:/usr/local/nginx/app/"
                            sh "ssh root@172.16.1.126 \"cd /usr/local/nginx/app;tar xf dist.tar.gz;rm -f dist.tar.gz;\""
                        }else if(workdir=="esign-auth-web"){
                            sh "ssh root@172.16.1.126 \"rm -rf /usr/local/nginx/authweb/*\""
                            sh "scp ${workdir}/${proName}/jenkins_tmp/dist/dist.tar.gz root@172.16.1.126:/usr/local/nginx/authweb/"
                            sh "ssh root@172.16.1.126 \"cd /usr/local/nginx/authweb;tar xf dist.tar.gz;rm -f dist.tar.gz;\""
                            }else{
                            sh "ssh root@172.16.1.126 \"rm -rf /usr/local/nginx/html/*\""
                            sh "scp ${workdir}/${proName}/jenkins_tmp/dist/dist.tar.gz root@172.16.1.126:/usr/local/nginx/html/"
                            sh "ssh root@172.16.1.126 \"cd /usr/local/nginx/html;tar xf dist.tar.gz;rm -f dist.tar.gz;\""
                        }
                        sh "exit 0"
                        tools.PrintMes("========部署成功========",'blue')
                }
            }
        }
    }
    post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq(pronames,'dev',"构建成功 ✅ ",Author,ChangeLog,pronames,instructions)
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq(pronames,'dev',"构建失败 ❌",Author,ChangeLog,pronames,instructions)
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq(pronames,'dev',"构建失败 ❌",Author,ChangeLog,pronames,"不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq(pronames,ImageTag,"构建失败 ❌",Author,ChangeLog,pronames,"暂停或中断")
                }
            }
        }
}
